import React, { memo, useRef } from 'react'
import type { FC, ReactNode } from 'react'

import { Carousel } from 'antd'
import type { CarouselRef } from 'antd/es/carousel'

import { AlbumWrapper } from './style'
import AreaHeaderV1 from '@/components/area-header-v1'
import { useAppSelector } from '@/store'
import NewAlbumItem from '@/components/new-album-item'

export interface IProps {
  children?: ReactNode
}

const NewAlbum: FC<IProps> = () => {
  // 从 redux 获取数据
  const { newAlbum } = useAppSelector((state) => ({
    newAlbum: state.recommend.newAlbum
  }))

  // 获取轮播图的Ref
  const bannerRef = useRef<CarouselRef>(null)

  // 轮播图事件处理
  function handlePrev() {
    bannerRef.current?.prev()
  }
  function handleNext() {
    bannerRef.current?.next()
  }

  return (
    <AlbumWrapper>
      <AreaHeaderV1 title="新碟上架" moreLink="/discover/album" />
      <div className="content">
        {/* 左右滚动按钮，鼠标移上去，背景精灵图平移，切换图片 */}
        <button
          className="sprite_02 arrow arrow-left"
          onClick={handlePrev}
        ></button>
        <div className="banner">
          {/* 轮播图 */}
          <Carousel ref={bannerRef} dots={false} speed={2000}>
            {/* 这里我们一共2页，第0页和第1页 */}
            {[0, 1].map((item) => {
              return (
                <div className="list" key={item}>
                  <div className="album-list">
                    {/* 由于我们从第0页开始，获取5条数据，所以公式如下： */}
                    {newAlbum.slice(item * 5, (item + 1) * 5).map((album) => {
                      return <NewAlbumItem key={album.id} itemData={album} />
                    })}
                  </div>
                </div>
              )
            })}
          </Carousel>
        </div>
        {/* 左右滚动按钮，鼠标移上去，背景精灵图平移，切换图片 */}
        <button
          className="sprite_02 arrow arrow-right"
          onClick={handleNext}
        ></button>
      </div>
    </AlbumWrapper>
  )
}

export default memo(NewAlbum)
